package io.task.message.socket.maintain;

import io.task.message.socket.ChannelContext;
import io.task.message.socket.Config;
import io.task.message.socket.lock.MapWithLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 一对一  (ChannelContext.id <--> ChannelContext)<br>
 */
public class Ids {
    private static final Logger log = LoggerFactory.getLogger(Ids.class);

    /**
     * key: ChannelContext对象的id字段
     * value: ChannelContext
     */
    private final MapWithLock<String, ChannelContext> map = new MapWithLock<>(new HashMap<String, ChannelContext>());

    /**
     * @param channelContext
     * @author tanyaowu
     */
    public void bind(ChannelContext channelContext) {

        try {
            String key = channelContext.getId();

            map.put(key, channelContext);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }

    /**
     * Find.
     *
     * @param id the id
     * @return the channel context
     */
    public ChannelContext find(Config config, String id) {


        return map.get(id);
    }

    /**
     * @return the cacheMap
     */
    public MapWithLock<String, ChannelContext> getMap() {
        return map;
    }

    /**
     * @param channelContext
     * @author tanyaowu
     */
    public void unbind(ChannelContext channelContext) {

        try {
            String key = channelContext.getId();

            map.remove(key);
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
